package znet

import (
	"encoding/json"
	"zinx-tianjing-study/ziface"
)

// 文件上传路由处理器
type FileUploadRouter struct {
	BaseRouter
	fileManager *FileTransferManager
}

func NewFileUploadRouter() *FileUploadRouter {
	return &FileUploadRouter{
		fileManager: GetFileManager(),
	}
}

// Handle 处理文件上传请求
func (r *FileUploadRouter) Handle(request ziface.IRequest) {
	switch request.GetMsgID() {
	case ziface.MsgIDFileStartUpload:
		r.handleStartUpload(request)
	case ziface.MsgIDFileChunkUpload:
		r.handleChunkUpload(request)
	case ziface.MsgIDFileUploadFinish:
		r.handleFinishUpload(request)
	}
}

// handleStartUpload 处理开始上传请求
func (r *FileUploadRouter) handleStartUpload(request ziface.IRequest) {
	var metadata FileMetadata
	if err := json.Unmarshal(request.GetRequestData(), &metadata); err != nil {
		r.sendError(request, "invalid metadata format")
		return
	}

	if err := r.fileManager.StartUpload(&metadata); err != nil {
		r.sendError(request, err.Error())
		return
	}

	// 发送成功响应
	response := struct {
		Message string `json:"message"`
	}{
		Message: "Upload started successfully",
	}
	r.sendResponse(request, ziface.MsgIDFileUploadSuccess, response)
}

// handleChunkUpload 处理文件块上传
func (r *FileUploadRouter) handleChunkUpload(request ziface.IRequest) {
	var chunk FileChunk
	if err := json.Unmarshal(request.GetRequestData(), &chunk); err != nil {
		r.sendError(request, "invalid chunk format")
		return
	}

	if err := r.fileManager.UploadChunk(&chunk); err != nil {
		r.sendError(request, err.Error())
		return
	}

	// 发送成功响应
	response := struct {
		Message    string `json:"message"`
		ChunkIndex int    `json:"chunkIndex"`
	}{
		Message:    "Chunk uploaded successfully",
		ChunkIndex: chunk.ChunkIndex,
	}
	r.sendResponse(request, ziface.MsgIDFileUploadSuccess, response)
}

// handleFinishUpload 处理完成上传请求
func (r *FileUploadRouter) handleFinishUpload(request ziface.IRequest) {
	var fileID string
	if err := json.Unmarshal(request.GetRequestData(), &fileID); err != nil {
		r.sendError(request, "invalid file ID format")
		return
	}

	if err := r.fileManager.FinishUpload(fileID); err != nil {
		r.sendError(request, err.Error())
		return
	}

	// 发送成功响应
	response := struct {
		Message string `json:"message"`
	}{
		Message: "File upload completed successfully",
	}
	r.sendResponse(request, ziface.MsgIDFileUploadSuccess, response)
}

// sendError 发送错误响应
func (r *FileUploadRouter) sendError(request ziface.IRequest, message string) {
	response := struct {
		Error string `json:"error"`
	}{
		Error: message,
	}
	r.sendResponse(request, ziface.MsgIDFileUploadError, response)
}

// sendResponse 发送响应
func (r *FileUploadRouter) sendResponse(request ziface.IRequest, msgID uint32, data interface{}) {
	responseBytes, _ := json.Marshal(data)
	request.GetConnection().Send(msgID, responseBytes)
}
